import axios from "axios";
import store from "@/store";
import { getToken } from "@/utils/auth";
import defaultSetting from "@/settings";

const service = axios.create({
    baseURL: defaultSetting.host,
    headers: {
        "Content-Type": "application/json",
    },
});

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const newConfig = config;
        if (store.state.user.token) {
            newConfig.headers.authorization = `Bearer ${getToken()}`;
        }
        return newConfig;
    },
    (error) => Promise.reject(error),
);
// 响应拦截器
service.interceptors.response.use(
    (response) => {
        const { data } = response;

        if (data.code === 500001) {
            store.dispatch("user/logout");
        }

        return data;
    },
    (error) => Promise.reject(error),
);

export default service;
